package org.hanbo.code.repository.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.hanbo.code.repository.exception.ErrorDescription;

public class CodeSnippetListViewActionBase
	extends GaeActionSupportBase
{
	private static final long serialVersionUID = 7264838396142616585L;
	private boolean isActionSuccessful;
	private ErrorDescription errorDesc;

	private List<CodeSnippetListItem> retrievedCodeSnippets;
	
	public CodeSnippetListViewActionBase()
	{
		isActionSuccessful = true;
		retrievedCodeSnippets = new ArrayList<CodeSnippetListItem>();
	}
	
	public String execute()
	{
		if (!checkLogin())
		{
			isActionSuccessful = false;
			return super.getCurrentStageValue();
		}
		
		if (!super.checkRegistration())
		{
			isActionSuccessful = false;
			return super.getCurrentStageValue();
		}
		
		return SUCCESS;
	}
	
	protected int parseCodeSnippetCount(HttpServletRequest req)
	{
		String retrievalCount = req.getParameter("count");
		
		if (StringUtils.isEmpty(retrievalCount))
		{
			throw new IllegalArgumentException(
				"Request does not contain \"count\" for searching code snippet"
			);
		}
		
		int snippetsCount = -1;
		try
		{
			snippetsCount = Integer.parseInt(retrievalCount);
			return snippetsCount;
		}
		catch(NumberFormatException e)
		{
			throw e;
		}
	}
		
	protected boolean getSuperActionSuccessful()
	{
		return isActionSuccessful;
	}
	
	protected void setErrorDescription(ErrorDescription errorDesc)
	{
		this.errorDesc = errorDesc;
	}
	
	protected void setRetrievedCodeSnippets(List<CodeSnippetListItem> viewItems)
	{
		this.retrievedCodeSnippets = viewItems;
	}
	
	public List<CodeSnippetListItem> getRetrievedCodeSnippets()
	{
		return this.retrievedCodeSnippets;
	}

	public boolean getRetrievedCodeSnippetsListEmpty()
	{
		return (this.retrievedCodeSnippets == null || this.retrievedCodeSnippets.size() <= 0);
	}
	
	public String getUserName()
	{
		return super.getLoggedInUser().getNickname();
	}
	
	public ErrorDescription getErrorDescription()
	{
		return errorDesc;
	}
	
	public String getLogoutUrl()
	{
		return super.createLogOutLink("../index.action");
	}
}
